package command

import (
	"dataconvertserver/server/appcore"
	"dataconvertserver/server/configclass"
	"dataconvertserver/utils/ormdb"
	"fmt"
	"strings"

	"gitlab.upchinaproduct.com/taf/tafgo/taf"
)

var loggerObj = taf.GetDayLogger("Command", 1)

func Init() {

}

func Version(param string) (string, error) {
	var versionInfo string
	versionInfo = versionInfo + "\n"
	versionInfo = versionInfo + "2024-04-23 17:17:00\n"
	loggerObj.Debugf(versionInfo)
	return versionInfo, nil
}

func Help(param string) (string, error) {
	var helpInfo string
	helpInfo = helpInfo + "\n\n"
	helpInfo = helpInfo + "---------------\n"
	helpInfo = helpInfo + "使用\"reload [数据库标签ID]\"重刷所有用户数据到目标数据库\n\n"
	helpInfo = helpInfo + "如果数据库ID只有一个可以省略不写\n\n"
	helpInfo = helpInfo + "例如: reload database_1\n\n"
	loggerObj.Debugf(helpInfo)
	return helpInfo, nil
}

/**
 * @Title 传入输入的命令 reload databases_1 获取数据库配置
 * @Description 如果数据库配置只有一个就直接返回 否则获取paramArray最后一个数据库配置
 */
func getOnlyDatabaseId(paramArray []string) (string, error) {
	var databaseId string
	if len(configclass.GetConfigManager().GetAllConfigs()) <= 1 {
		for databaseId = range configclass.GetConfigManager().GetAllConfigs() {
			break
		}
	} else {
		databaseId = paramArray[len(paramArray)-1]
	}
	return databaseId, nil
}

func HandleRawConvert(param string) (string, error) {
	loggerObj.Debugf("{HandleRawConvert param}|%s", param)
	var paramArray = strings.Split(param, " ")
	var databaseId, _ = getOnlyDatabaseId(paramArray)
	if databaseId == "" {
		loggerObj.Debugf("{HandleRawConvertError databaseId not found}|%s", databaseId)
		return "", fmt.Errorf("{HandleRawConvertError databaseId not found}|%s", databaseId)
	}
	var sourceDb, _ = ormdb.GetSourceDb(databaseId)
	var destinationDb, _ = ormdb.GetDestinationDb(databaseId)
	// var configClass, _ = configclass.GetConfigManager().GetConfig(databaseId)
	// var sourceConfig = configClass.Source
	//var destinationConfig = configStruct[databaseId].Destination
	if sourceDb == nil || destinationDb == nil {
		loggerObj.Debugf("{HandleRawConvertError databaseId not found}|%s", databaseId)
		return "", fmt.Errorf("{HandleRawConvertError databaseId not found}|%s", databaseId)
	}
	// sourceConfig.IncrementDatetime = utils.EarliestTimeStr()
	//go crontab.ConvertSourceToDestination(loggerObj, sourceDb, &sourceConfig, destinationDb, &destinationConfig)
	go func() {
		var retSrc, errHandleSource = appcore.HandleSourceDatabase(loggerObj, databaseId, "0000-00-00 00:00:00")
		if retSrc != 0 || errHandleSource != nil {
			loggerObj.Debugf("{warning HandleSourceDatabase databaseId^ret^error}|%s|%d|%s", databaseId, retSrc, errHandleSource)
		} else {
			loggerObj.Debugf("{success HandleSourceDatabase databaseId^ret^error}|%s|%d|%s", databaseId, retSrc, errHandleSource)
		}
	}()
	return "cmd_async", nil
}
